<template>
  <div class="flex flex-col previewPage">
    <a-layout class="relative flex-1 bg-inherit">
      <div class="preview-content">
        <iframe
          ref="iframeRef"
          frameBorder="0"
          allowFullScreen="true"
          class="perview-iframe"
          :src="previewUrl"
          @load="initPage"
        />
      </div>
    </a-layout>
  </div>
</template>
<script lang="ts" setup>
import { nextTick, onMounted, onUnmounted, reactive, ref, toRaw, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import IframeHelper from '@/utils/iframeHelper'
import { storage } from '@/utils/storage'
import { H5_PREVIEW_URL } from './state'
import apis from '@/apis'
const {
  template: { template_get }
} = apis
// console.log('JSON.parse(storage.get()): ', storage.get('style_data'))
const styleState = ref()
if (storage.get('style_data')) {
  styleState.value = JSON.parse(storage.get('style_data').replace(/\\"/g, '"'))
}
interface IdState {
  template_id: string
  advertiser_id: string
  video_id: string
  image_id: string
  article_id: string
}
const idState = reactive<IdState>({
  template_id: '',
  advertiser_id: '',
  video_id: '',
  image_id: '',
  article_id: ''
})
const router = useRouter()
const route = useRoute()
const previewUrl = ref()
const iframeRef = ref()
const getUrl = () => {
  // const { hostname } = window.location
  // const port = 7200
  // const baseUrl = `http://${hostname}:${port}`
  return H5_PREVIEW_URL
}

let iframeHelper: IframeHelper
const initPreviewUrl = () => {
  // 本地调试需要启动qw-wxmini-mall-client
  const baseUrl = getUrl()
  const host = window.location.origin
  console.log('baseUrl', baseUrl, host)
  previewUrl.value = `${baseUrl}home?preview=${host}&advertiser_id=${idState.advertiser_id}&video_id=${idState.video_id}&image_id=${idState.image_id}&article_id=${idState.article_id}`
}

const initMessage = () => {
  console.log('执行了')
  const targetOrigin = getUrl()
  iframeHelper = new IframeHelper(iframeRef.value.contentWindow, targetOrigin)
}
const timer = ref()
const createSetInterval = () => {
  stopSetInterval()
  timer.value = setInterval(() => {
    initPage()
  }, 1000)
}
// 关闭轮询
const stopSetInterval = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}
// 加载页面数据
const initPage = () => {
  console.log('轮询', styleState.value)
  if (!styleState.value) return createSetInterval()
  stopSetInterval()
  setTimeout(() => {
    const obj = JSON.parse(JSON.stringify(toRaw(styleState)))
    console.log('传递给iframe的数据：', obj)
    iframeHelper.emit('init-page', obj)
  }, 300)
}
const getTemplateData = async (id: string) => {
  const result: any = await template_get({ id })
  console.log('result: ', result)
  styleState.value = JSON.parse(result.template.data.replace(/\\"/g, '"'))
}
initPreviewUrl()
watch(
  () => route.name,
  (val) => {
    storage.remove('previewToken')
  },
  { deep: true, immediate: true }
)
onMounted(async () => {
  initMessage()
  const token = router.currentRoute.value.query.access_token
  if (token) {
    storage.set('previewToken', token)
  }

  idState.template_id = router.currentRoute.value.query.template_id as string
  idState.advertiser_id = router.currentRoute.value.query.advertiser_id as string
  idState.video_id = router.currentRoute.value.query.video_id as string
  idState.image_id = router.currentRoute.value.query.image_id as string
  idState.article_id = router.currentRoute.value.query.article_id as string
  console.log('idState: ', idState)
  if (idState.template_id) {
    await getTemplateData(idState.template_id)
  }
})
onUnmounted(() => {
  storage.remove('previewToken')
  iframeHelper.destroy()
  stopSetInterval()
})
</script>
<style scoped lang="less">
.previewPage {
  width: 100%;
  height: 100%;
  min-width: 1200px;
  background-color: var(--editor-bg);
  .anticon {
    cursor: pointer;
  }
  .preview-content {
    position: absolute;
    left: 0;
    right: 0;
    margin: 100px auto;
    background-color: #fff;
    height: 667px;
    width: 375px;
    .perview-iframe {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
